"""
    Contains MassAction class and special registrar for mass actions.
"""

from turbogears import widgets, identity
from sqlobject import declarative
from mnemoply.utils import IdsValidator

class MassActionsRegistry(object):
    """
        Registrar for MassAction inheritors.
    """

    def __init__(self):
        self.actions = {}

    def register(self, mass_action):
        class_name = mass_action.target_class.__name__
        action_name = mass_action.name

        if not class_name in self.actions:
            self.actions[class_name] = {}

        self.actions[class_name][action_name] = mass_action

    def getActionsForClass(self, target_class):
        class_name = target_class.__name__
        actions = [ma for ma in self.actions.get(class_name, {}).values()
                   if identity.has_any_permission('dba', target_class.getModelName() + '/' + ma.name)]
        return actions
    
    def getAction(self, class_name, action_name):
        return self.actions[class_name][action_name]

# Create the instance of MassActionsRegistry
# We hope it will be a singleton
registry = MassActionsRegistry()

class MassActionForm(widgets.TableForm):
    """
        Basic UI form for MassAction inheritors.
        Contains callable ids, referer and 'Execute' button.
    """

    def __init__(self, name, fields=None):
        if fields is None:
            fields = []

        fields.append(widgets.HiddenField(
            name="ids",
            validator=IdsValidator,
        ))

        fields.append(widgets.HiddenField(
            name="referer",
        ))

        widgets.TableForm.__init__(self,
            name="ma_" + name,
            fields=fields,
            submit_text=_("Execute"),
        )

class MassAction(object):
    """
        Base class for action classes, whitch we use in UI lookups.
    """

    __metaclass__ = declarative.DeclarativeMeta

    form = None
    read_only = False
    title = None
    name = None
    target_class = None
    obj = None
    flash_message = None
    successfully_execute = True
    display_on_lookup = True

    def __classinit__(cls, new_attrs):
        """
            Automatic registration in registry after class creation.
        """

        if cls.__name__ != "MassAction":
            registry.register(cls())

    def __init__(self, *k, **kw):
        super(MassAction, self).__init__(*k, **kw)

        if not self.form:
            self.form = MassActionForm(name=self.name)

        assert self.title
        assert self.name
        assert self.target_class

    def get_obj(self):
        return self.obj

    def inject_object(self, obj):
        self.obj = obj

    def getURL(self, method=''):
        """
            Returns special URL for each MassAction inheritor.
        """

        return '/MassActions/%s-%s/%s' % (
            self.target_class.__name__, self.name, method)

    url = property(getURL)
